package service

import (
	"dataconvertserver/server/appcore"
	"dataconvertserver/taf-protocol/CRM"
	"dataconvertserver/utils/ormdb"
	"fmt"
	"strings"

	"gitlab.upchinaproduct.com/taf/tafgo/taf/util/rogger"
	"gorm.io/gorm"
)

func Init() {
}

// 发送通知写入表
func SendKeyTellMe(loggerObj *rogger.Logger, req *CRM.SendKeyTellMeReq, rsp *CRM.SendKeyTellMeRsp) (int32, error) {
	loggerObj.Debugf("{start req}|%s", req.Display())
	rsp.Ret = 1
	rsp.Msg = "我处理完成啦"
	return 0, nil
}

// 发送sql语句直接执行写入表
func SendSqlExecute(loggerObj *rogger.Logger, req *CRM.SendSqlExecuteReq, rsp *CRM.SendSqlExecuteRsp) (int32, error) {
	var ret int32
	var errorString error
	var destinationDb, _ = ormdb.GetDestinationDb(req.DatabaseId)
	loggerObj.Debugf("{start req}|%s", req.Display())

	if destinationDb == nil {
		ret = -2
		rsp.Ret = ret
		rsp.Msg = req.DatabaseId + " is null"
		return ret, errorString
	}
	var result *gorm.DB
	var databaseListTemp []map[string]interface{}
	loggerObj.Debugf("{execute SQL}|%s", req.ExplainSql)
	if req.Statement == "select" {
		result = destinationDb.Raw(req.ExplainSql).Scan(&databaseListTemp)
		loggerObj.Debugf("{execute SQL result}|%+v", result)
		loggerObj.Debugf("{execute SQL result list length}|%+v", len(databaseListTemp))
	} else {
		result = destinationDb.Exec(req.ExplainSql)
		loggerObj.Debugf("{execute SQL result}|%+v", result)
	}
	if result != nil && result.Error != nil {
		ret = -3
		errorString = fmt.Errorf("failed to execute SQL statement %+v", result.Error)
		loggerObj.Debugf("{failed to execute SQL statement}|%+v", result.Error)
		return ret, errorString
	}
	ret = 0
	rsp.Ret = ret
	rsp.Msg = "我处理完成啦"
	loggerObj.Debugf("{Execute rows successfully.}|%+v", result)
	return ret, errorString
}

// 发送sql语句直接执行写入表
func SendValueExecute(loggerObj *rogger.Logger, req *CRM.SendValueExecuteReq, rsp *CRM.SendValueExecuteRsp) (int32, error) {
	var ret int32
	var errorString error
	var sourceDb, _ = ormdb.GetSourceDb(req.DatabaseId)
	var destinationDb, _ = ormdb.GetDestinationDb(req.DatabaseId)
	loggerObj.Debugf("{start req}|%s", req.Display())
	if sourceDb == nil || destinationDb == nil {
		ret = -2
		rsp.Ret = ret
		rsp.Msg = req.DatabaseId + " not found"
		return ret, errorString
	}
	if strings.TrimSpace(req.DatabaseId) == "" || strings.TrimSpace(req.CacheKey) == "" || strings.TrimSpace(req.CacheValue) == "" {
		ret = -3
		rsp.Ret = ret
		rsp.Msg = "req param null"
		return ret, errorString
	}
	// 创建一个新的 map 并设置各个字段的值
	entry := map[string]interface{}{
		"USERID":            req.CacheKey,
		"VALUE":             req.CacheValue,
		"sDCacheExpireTime": "2000-01-01T00:00:00Z",
		"auto_updatetime":   "2000-01-01T00:00:00Z",
	}
	// 将数据发送到通道
	task := appcore.Task{Id: 1, DatabaseID: req.DatabaseId, DataBaseKV: entry}
	appcore.GetWorkerPoolInstance().AddTask(task)
	loggerObj.Debugf("{task added to WorkerPool}")

	ret = 0
	rsp.Ret = ret
	rsp.Msg = "我处理完成啦"
	return ret, errorString
}
